import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../utils/image_picker_helper.dart';
import '../utils/loading_util.dart';
import '../services/index.dart';

/// 图片选择配置
class ImagePickerConfig {
  final double? maxWidth;
  final double? maxHeight;
  final int imageQuality;
  final bool showCamera;      // 是否显示相机选项
  final bool showGallery;     // 是否显示相册选项
  final String title;         // 弹出框标题
  final String cameraText;    // 相机按钮文字
  final String galleryText;   // 相册按钮文字
  final String cancelText;    // 取消按钮文字
  
  const ImagePickerConfig({
    this.maxWidth = 1080,
    this.maxHeight = 1080,
    this.imageQuality = 85,
    this.showCamera = true,
    this.showGallery = true,
    this.title = '选择头像',
    this.cameraText = '拍照',
    this.galleryText = '从相册选择',
    this.cancelText = '取消',
  });
}

/// 图片选择底部弹出组件
/// 
/// 提供统一的图片选择UI交互，包括相机拍照和相册选择
/// 可在任何页面复用，自动处理权限申请和错误处理
class ImagePickerBottomSheet {
  static const String tag = 'ImagePickerBottomSheet';

  /// 显示图片选择底部弹出框
  /// 
  /// [config] 选择配置
  /// [onImageSelected] 图片选择成功回调
  /// [onError] 错误处理回调
  static Future<void> show({
    ImagePickerConfig config = const ImagePickerConfig(),
    required Function(String imagePath) onImageSelected,
    Function(String errorMessage, ImagePickerError? error)? onError,
  }) async {
    await Get.bottomSheet(
      _ImagePickerBottomSheetWidget(
        config: config,
        onImageSelected: onImageSelected,
        onError: onError,
      ),
      isScrollControlled: true,
    );
  }
}

/// 图片选择底部弹出框UI组件
class _ImagePickerBottomSheetWidget extends StatelessWidget {
  final ImagePickerConfig config;
  final Function(String imagePath) onImageSelected;
  final Function(String errorMessage, ImagePickerError? error)? onError;
  
  const _ImagePickerBottomSheetWidget({
    required this.config,
    required this.onImageSelected,
    this.onError,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 顶部指示器
            Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.only(top: 12, bottom: 20),
              decoration: BoxDecoration(
                color: Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            
            // 标题
            Text(
              config.title,
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 20),
            
            // 选项按钮
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                  // 相机拍照选项
                  if (config.showCamera)
                    _buildSelectionOption(
                      icon: Icons.camera_alt,
                      title: config.cameraText,
                      subtitle: '使用相机拍摄新照片',
                      onTap: () => _pickImageFromCamera(),
                    ),
                  
                  if (config.showCamera && config.showGallery)
                    const SizedBox(height: 12),
                  
                  // 相册选择选项
                  if (config.showGallery)
                    _buildSelectionOption(
                      icon: Icons.photo_library,
                      title: config.galleryText,
                      subtitle: '选择已有的照片',
                      onTap: () => _pickImageFromGallery(),
                    ),
                  
                  const SizedBox(height: 20),
                  
                  // 取消按钮
                  SizedBox(
                    width: double.infinity,
                    child: TextButton(
                      onPressed: () => Get.back(),
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text(
                        config.cancelText,
                        style: const TextStyle(
                          fontSize: 16,
                          color: Colors.grey,
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建选择选项
  Widget _buildSelectionOption({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey.shade200),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          children: [
            Container(
              width: 48,
              height: 48,
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                icon,
                color: Colors.blue.shade600,
                size: 24,
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Colors.black87,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: Colors.grey.shade400,
            ),
          ],
        ),
      ),
    );
  }

  /// 从相机拍照
  Future<void> _pickImageFromCamera() async {
    Get.back(); // 关闭底部弹出框
    
    try {
      final result = await ImagePickerHelper().pickImageFromCamera(
        maxWidth: config.maxWidth,
        maxHeight: config.maxHeight,
        imageQuality: config.imageQuality,
      );
      
      if (result.success && result.imagePath != null) {
        onImageSelected(result.imagePath!);
      } else if (result.errorMessage != null) {
        await _handleImagePickerError(result.errorMessage!, result.error);
      }
      
    } catch (e) {
      await _handleImagePickerError('拍照失败，请重试', ImagePickerError.unknown);
    }
  }

  /// 从相册选择
  Future<void> _pickImageFromGallery() async {
    Get.back(); // 关闭底部弹出框
    
    try {
      final result = await ImagePickerHelper().pickImageFromGallery(
        maxWidth: config.maxWidth,
        maxHeight: config.maxHeight,
        imageQuality: config.imageQuality,
      );
      
      if (result.success && result.imagePath != null) {
        onImageSelected(result.imagePath!);
      } else if (result.errorMessage != null) {
        await _handleImagePickerError(result.errorMessage!, result.error);
      }
      
    } catch (e) {
      await _handleImagePickerError('选择图片失败，请重试', ImagePickerError.unknown);
    }
  }

  /// 处理图片选择错误
  Future<void> _handleImagePickerError(
    String errorMessage, 
    ImagePickerError? error,
  ) async {
    // 如果提供了自定义错误处理回调，使用它
    if (onError != null) {
      onError!(errorMessage, error);
      return;
    }
    
    // 默认错误处理
    switch (error) {
      case ImagePickerError.permanentlyDenied:
        await _showPermissionSettingsDialog(errorMessage);
        break;
      case ImagePickerError.permissionDenied:
        _showErrorSnackbar(errorMessage);
        break;
      case ImagePickerError.noImageSelected:
        // 用户取消，不显示错误
        break;
      default:
        _showErrorSnackbar(errorMessage);
        break;
    }
  }

  /// 显示权限设置对话框
  Future<void> _showPermissionSettingsDialog(String message) async {
    final shouldOpenSettings = await Get.dialog<bool>(
      AlertDialog(
        title: const Text('需要权限'),
        content: Text(
          '$message\n\n操作步骤：\n'
          '1. 点击"前往设置"\n'
          '2. 找到应用权限\n'
          '3. 开启相应权限',
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: const Text('前往设置'),
          ),
        ],
      ),
    ) ?? false;
    
    if (shouldOpenSettings) {
      final permissionService = Get.find<PermissionService>();
      await permissionService.openAppSettings();
    }
  }

  /// 显示错误提示
  void _showErrorSnackbar(String message) {
    LoadingUtil.error(message, duration: const Duration(seconds: 3));
  }
}
